package net;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天的客户端对象
 */
public class ChatClient {
    private Socket socket;
    public ChatClient(){
        try {
            System.out.println("客户端启动。。。");
            socket = new Socket("127.0.0.1",8088);
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }
    public void start() {
        Scanner sc = null;
        PrintWriter pw = null;
        BufferedReader br=null;
        try {
            //1.获取输出流对象，能够一次写一行
            pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream(), StandardCharsets.UTF_8)), true);

            //2.写数据
            new Thread(new ServerHandler()).start(); //读取服务端的数据
            sc = new Scanner(System.in);
            System.out.println("请输入数据：");
            while (true) {
                String content = sc.nextLine(); //这个方法是一个阻塞式方法，没有输入就会在这里阻塞
                if ("exit".equalsIgnoreCase(content)) break;
                pw.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //3.释放资源
            if (sc != null) sc.close();
            if (pw != null) pw.close();
            if (socket != null) try {socket.close();} catch (IOException e) {e.printStackTrace();}
        }
    }
    //构建客户端任务类型，负责处理服务端反悔的数据
    private class ServerHandler implements Runnable {
        public void run(){
            BufferedReader br = null;
            try {
                br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(), StandardCharsets.UTF_8));
                //读取服务端反悔的数据
                String content = null;
                while ((content = br.readLine())!= null) {
                    System.out.println(content);
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new ChatClient().start();
    }
}
